<template>
  <div class="chat-view">
    <!-- 聊天头部 -->
    <div class="chat-header pixel-border">
      <div class="header-left">
        <div class="ai-avatar pixel-border">
          🤖
        </div>
        <div class="ai-info">
          <h2 class="ai-name">教室查询助手</h2>
          <div class="ai-status">
            <px-tag
              :theme="isSystemReady ? 'success' : 'warning'"
              size="small"
            >
              {{ isSystemReady ? '就绪' : '初始化中' }}
            </px-tag>
            <px-tag
              :theme="systemStore.systemStatus.session_active ? 'info' : 'danger'"
              size="small"
              v-if="!systemStore.systemStatus.session_active"
            >
              未登录
            </px-tag>
          </div>
        </div>
      </div>
      <div class="header-right">
        <px-button
          variant="outline"
          size="small"
          @click="clearChat"
        >
          清空
        </px-button>
      </div>
    </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-wrapper"
          :class="`message-${message.type}`"
        >
          <div class="message-content pixel-border">
            <div class="message-header">
              <span class="message-sender">
                {{ getSenderName(message.type) }}
              </span>
              <span class="message-time">
                {{ formatTime(message.timestamp) }}
              </span>
            </div>
            <div class="message-text">
              <template v-if="message.loading">
                <px-space align="center">
                  <div class="typing-indicator">
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                  </div>
                  <span>AI正在思考...</span>
                </px-space>
              </template>
              <template v-else>
                <MarkdownRenderer :content="message.content" />
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input pixel-border">
        <div class="input-container">
          <px-input
            v-model="currentMessage"
            placeholder="请输入您的查询，例如：查一下现在思源楼哪些教室有空"
            :disabled="!isSystemReady || isLoading"
            @keyup.enter="sendMessage"
            size="large"
            class="message-input"
          />
          <px-button
            @click="sendMessage"
            :disabled="!isSystemReady || isLoading || !currentMessage.trim()"
            :loading="isLoading"
            theme="primary"
            size="large"
            class="send-button"
          >
            发送
          </px-button>
        </div>

        <!-- 快捷查询按钮 -->
        <div class="quick-queries" v-if="!systemStore.systemStatus.session_active">
          <p class="quick-query-title">
            <px-icon-warning />
            服务器未登录教育系统，无法进行教室查询
          </p>
          <px-button
            theme="success"
            @click="$router.push('/login')"
            size="small"
          >
            前往登录
          </px-button>
        </div>

        <div class="quick-queries" v-else-if="isSystemReady">
          <p class="quick-query-title">快捷查询：</p>
          <px-space wrap>
            <px-button
              v-for="query in quickQueries"
              :key="query.id"
              variant="outline"
              size="small"
              @click="useQuickQuery(query.text)"
            >
              {{ query.label }}
            </px-button>
          </px-space>
        </div>

        <div class="quick-queries" v-else>
          <p class="quick-query-title">
            ℹ️ 系统正在初始化中，请稍候...
          </p>
        </div>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useSystemStore } from '@/stores/system'
import type { ChatMessage } from '@/types'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

const router = useRouter()
const systemStore = useSystemStore()

// 响应式数据
const messages = ref<ChatMessage[]>([])
const currentMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement>()

// 计算属性
const isSystemReady = computed(() => systemStore.isSystemReady)

// 快捷查询
const quickQueries = ref([
  { id: 1, label: '思源楼空闲教室', text: '查一下现在思源楼哪些教室有空' },
  { id: 2, label: '明天思西教室', text: '明天思源西楼的空闲教室' },
  { id: 3, label: '逸夫楼下午教室', text: '逸夫教学楼下午的空教室' },
  { id: 4, label: '九教第1-2节', text: '第九教学楼第1-2节有哪些教室可用' },
  { id: 5, label: '机械楼明天上午', text: '机械楼明天上午有空的教室吗' }
])

// 方法
const addMessage = (type: ChatMessage['type'], content: string, loading = false) => {
  const message: ChatMessage = {
    id: Date.now().toString() + Math.random(),
    type,
    content,
    timestamp: new Date(),
    loading
  }
  messages.value.push(message)
  nextTick(() => {
    scrollToBottom()
  })
  return message
}

const updateMessage = (messageId: string, content: string, loading = false) => {
  const message = messages.value.find(m => m.id === messageId)
  if (message) {
    message.content = content
    message.loading = loading
    message.timestamp = new Date()
  }
}

const removeMessage = (messageId: string) => {
  const index = messages.value.findIndex(m => m.id === messageId)
  if (index > -1) {
    messages.value.splice(index, 1)
  }
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const getSenderName = (type: ChatMessage['type']) => {
  switch (type) {
    case 'user':
      return '👤 用户'
    case 'assistant':
      return '🤖 AI助手'
    case 'system':
      return '⚙️ 系统'
    default:
      return '📝 未知'
  }
}

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const useQuickQuery = (queryText: string) => {
  currentMessage.value = queryText
  sendMessage()
}

const clearChat = () => {
  messages.value = []
  addMessage('system', '对话已清空，您可以开始新的查询')
}

const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value || !isSystemReady.value) {
    return
  }

  // 检查服务器是否有会话
  if (!systemStore.systemStatus.session_active) {
    addMessage('system', '服务器未登录教育系统，无法进行教室查询')
    router.push('/login')
    return
  }

  const userMessage = currentMessage.value.trim()
  currentMessage.value = ''

  // 添加用户消息
  addMessage('user', userMessage)

  // 添加加载中的AI消息，显示更多信息
  const loadingMessage = addMessage('assistant', '🔍 正在查询教室信息，请稍候...', true)

  isLoading.value = true
  let loadingTimeout: NodeJS.Timeout | null = null

  // 设置加载状态更新
  loadingTimeout = setTimeout(() => {
    updateMessage(loadingMessage.id, '🔍 查询中，教室数据较多需要一些时间...')
  }, 3000)

  try {
    const response = await systemStore.queryClassroom({
      message: userMessage
    })

    if (loadingTimeout) {
      clearTimeout(loadingTimeout)
    }

    if (response.success) {
      updateMessage(loadingMessage.id, response.response)
    } else {
      updateMessage(
        loadingMessage.id,
        `查询失败: ${response.error || '未知错误'}`
      )
    }
  } catch (error: any) {
    console.error('查询失败:', error)

    if (loadingTimeout) {
      clearTimeout(loadingTimeout)
    }

    let errorMessage = '查询失败，请检查网络连接或稍后重试'

    // 根据错误类型显示不同的消息
    if (error.code === 'ECONNABORTED') {
      errorMessage = '查询超时，教室数据较多，请稍后重试'
    } else if (error.response?.status === 503) {
      errorMessage = '服务暂时不可用，请稍后重试'
    } else if (error.message?.includes('timeout')) {
      errorMessage = '查询超时，请稍后重试'
    }

    updateMessage(loadingMessage.id, errorMessage)
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

onMounted(async () => {
  // 先检测系统状态
  try {
    await systemStore.fetchSystemStatus()
  } catch (error) {
    console.error('检测系统状态失败:', error)
    addMessage('system', '无法连接到后端服务，请检查网络连接')
    return
  }

  // 添加欢迎消息
  addMessage(
    'system',
    '欢迎使用北交大教室查询助手！系统已配置全局会话，您可以直接开始查询。'
  )

  if (!isSystemReady.value) {
    addMessage(
      'system',
      '系统正在初始化中，请稍等...'
    )
  } else if (systemStore.systemStatus.session_active) {
    // 如果服务器有会话，直接可以使用
    addMessage(
      'system',
      '服务器已登录教育系统，您可以立即使用教室查询功能。'
    )
  } else {
    // 如果服务器没有会话，才需要用户登录
    addMessage(
      'system',
      '服务器未登录教育系统，需要先进行系统登录。'
    )
  }
})
</script>

<style scoped>
.chat-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-header {
  background: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 3px solid var(--pixel-primary);
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.8);
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.ai-avatar {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background-color: var(--pixel-primary);
  color: white;
  flex-shrink: 0;
}

.ai-info {
  flex: 1;
  min-width: 0;
}

.ai-name {
  font-size: 16px;
  margin-bottom: 4px;
  color: var(--pixel-primary);
  font-weight: bold;
}

.ai-status {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 12px 8px;
  background-color: #f5f5f5;
}

.message-wrapper {
  margin-bottom: 12px;
  display: flex;
}

.message-wrapper.message-user {
  justify-content: flex-end;
}

.message-wrapper.message-system {
  justify-content: center;
}

.message-content {
  max-width: 85%;
  padding: 10px 12px;
  background: white;
  position: relative;
  border: 2px solid #333;
  box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.8);
}

.message-user .message-content {
  background-color: var(--pixel-primary);
  color: white;
}

.message-system .message-content {
  background-color: var(--pixel-warning);
  color: var(--pixel-dark);
  max-width: 90%;
  text-align: center;
  font-size: 12px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 10px;
  opacity: 0.8;
}

.message-sender {
  font-weight: bold;
  flex-shrink: 0;
}

.message-time {
  flex-shrink: 0;
}

.message-text {
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  margin-right: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background-color: var(--pixel-primary);
  display: inline-block;
  animation: pixelBlink 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

.chat-input {
  background: white;
  padding: 12px 16px;
  border-top: 3px solid var(--pixel-primary);
  box-shadow: 0 -2px 0 rgba(0, 0, 0, 0.8);
  flex-shrink: 0;
}

.input-container {
  display: flex;
  gap: 8px;
  align-items: flex-end;
  margin-bottom: 12px;
}

.message-input {
  flex: 1;
}

.send-button {
  flex-shrink: 0;
  min-width: 70px;
}

.quick-queries {
  text-align: center;
}

.quick-query-title {
  font-size: 12px;
  margin-bottom: 8px;
  color: var(--pixel-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  line-height: 1.3;
}

@keyframes pixelBlink {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 手机端专门优化 */
@media (max-width: 768px) {
  .chat-view {
    height: 100vh;
    padding: 0;
  }

  .chat-header {
    padding: 8px 12px;
  }

  .header-left {
    gap: 8px;
  }

  .ai-avatar {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }

  .ai-name {
    font-size: 14px;
  }

  .ai-status .px-tag {
    font-size: 10px;
  }

  .chat-messages {
    padding: 8px 4px;
  }

  .message-wrapper {
    margin-bottom: 8px;
  }

  .message-content {
    max-width: 90%;
    padding: 8px 10px;
  }

  .message-text {
    font-size: 12px;
  }

  .chat-input {
    padding: 8px 12px;
  }

  .input-container {
    gap: 6px;
  }

  .send-button {
    min-width: 60px;
  }

  .quick-query-title {
    font-size: 11px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .ai-name {
    font-size: 12px;
  }

  .message-text {
    font-size: 11px;
  }

  .quick-queries .px-space {
    justify-content: center;
  }

  .quick-queries .px-button {
    font-size: 10px;
    padding: 4px 8px;
  }
}
</style>